# Create some test data for our catalog in the form of a list of dictionaries. books = [ {'id': 0, 'title': 'A Fire Upon the Deep', 'author': 'Vernor Vinge', 'first_sentence': 'The coldsleep itself was dreamless.', 'year_published': '1992'}, {'id': 1, 'title': 'The Ones Who Walk Away From Omelas', 'author': 'Ursula K. Le Guin', 'first_sentence': 'With a clamor of bells that set the swallows soaring, the Festival of Summer came to the city Omelas, bright-towered by the sea.', 'published': '1973'}, {'id': 2, 'title': 'Dhalgren', 'author': 'Samuel R. Delany', 'first_sentence': 'to wound the autumnal city.', 'published': '1975'} ]
# 省略了部分初始化 app 代码 from flask import request, jsonify
@app.route('/api/v1/resources/books', methods=['GET']) defapi_id(): # Check if an ID was provided as part of the URL. # If ID is provided, assign it to a variable. # If no ID is provided, display an error in the browser. if'id'in request.args: id = int(request.args['id']) else: return"Error: No id field provided. Please specify an id."
# Create an empty list for our results results = []
# Loop through the data and match results that fit the requested ID. # IDs are unique, but other fields might return many results for book in books: if book['id'] == id: results.append(book)
# Use the jsonify function from Flask to convert our list of # Python dictionaries to the JSON format. return jsonify(results)
以上的 API 可以通过链接 http://<host>/api/v1/resources/books?id=1 查询 id 为 1 的书籍。
定制化响应异常
在 API 服务中异常处理包括了本身代码异常处理,以及提供服务的异常处理。服务的异常包括请求格式不符合要求、连接异常等,某些异常有专门的响应代码表达响应的结果。为了规范响应,使用 errorhandler 可以通过定制化响应的响应结果: